package com.yu.demo.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yu.demo.commons.enums.UserResultEnum;
import com.yu.demo.commons.ex.UserException;
import com.yu.demo.dao.entity.User;
import com.yu.demo.dao.mapper.UserMapper;
import com.yu.demo.pojo.dto.UserDTO;
import com.yu.demo.pojo.query.UserQuery;
import com.yu.demo.pojo.vo.ResultVO;
import com.yu.demo.pojo.vo.UserVo;
import com.yu.demo.service.UserService;
import com.yu.demo.utils.CopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description:
 * @Author: WengYu
 * @CreateTime: 2022/05/31 14:57
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public Boolean add(UserDTO userDTO) {
        log.info("当前UserDTO--->{}",userDTO);
        if (null == userDTO) {
            throw new UserException(UserResultEnum.USER_INPUT_ERROR);
        }
        if (StringUtils.isEmpty(userDTO.getPassword())) {
            throw new UserException(UserResultEnum.USER_PWD_NOT_EMPTY);
        }
        if (StringUtils.isEmpty(userDTO.getCode())){
            throw new UserException(UserResultEnum.USER_CODE_NOT_EMPTY);
        }

        int code = userMapper.getCode(userDTO.getCode());
        if (code > 0){
            throw new UserException(UserResultEnum.USER_CODE_IS_EXIST);
        }
        User user = CopyUtil.copy(userDTO, User.class);
        return userMapper.insert(user) > 0;
    }

    @Override
    public Boolean delete(Long id) {
        log.info("当前id--->{}",id);
        if (id < 0) {
            throw new UserException(UserResultEnum.USER_ID_ERROR);
        }
        return userMapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public Boolean update(UserDTO userDTO) {
        log.info("当前UserDTO--->{}",userDTO);
        if (null == userDTO) {
            throw new UserException(UserResultEnum.USER_INPUT_ERROR);
        }
        User user = CopyUtil.copy(userDTO, User.class);
        return userMapper.updateByPrimaryKeySelective(user) > 0;
    }

    @Override
    public ResultVO<List<UserVo>> search(UserQuery userQuery) {
        log.info("当前UserQuery--->{}",userQuery);
        if (null == userQuery) {
            throw new UserException(UserResultEnum.USER_INPUT_ERROR);
        }
        PageHelper.startPage(userQuery.getPageNum(), userQuery.getPageSize());
        User user = CopyUtil.copy(userQuery, User.class);

        List<User> users = userMapper.getUserList(user);
        Page page = (Page) users;

        List<UserVo> userVoList = CopyUtil.copyList(page, UserVo.class);
        ResultVO<List<UserVo>> resultVO = new ResultVO<>();
        resultVO.setResult(userVoList);
        resultVO.setTotal(page.getTotal());

        return resultVO;
    }

}
